<?php

namespace Frieza\Modules\Blank\Controllers;

use Doraemon\amqp\CommunityQueue;
use Doraemon\tools\Ip;
use Encore\Admin\Grid;
use Doraemon\cache\Queue;
use Doraemon\model\Member;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Encore\Admin\Layout\Row;
use Illuminate\Http\Request;
use Doraemon\tools\BlockType;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Doraemon\tools\PointConfig;
use Encore\Admin\Facades\Admin;
use Hhzbeads\Point\PointClient;
use Biz\pockets\excel\DownExcel;
use Doraemon\cache\BlankCounter;
use Encore\Admin\Layout\Content;
use Doraemon\model\MyArticleList;
use Illuminate\Support\MessageBag;
use Doraemon\model\Blank as dbBlank;
use App\Http\Controllers\Controller;
use Doraemon\service\Blank as sBlank;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\model\ContentSignExtend;
use Doraemon\service\ContentCategory;
use Doraemon\service\Member as sMember;
use Doraemon\model\Comment as DbComment;
use Doraemon\service\AdmBlank\Schedule;
use Doraemon\service\AdmBlank\BlankSearch;
use Doraemon\service\AdmBlank\FilterConfig;
use Doraemon\service\UserGrowth\AutoAction;
use Doraemon\model\AdminAccount\AdminAccount;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdminAccount\AdminAccountOperate;
use Doraemon\model\ContentCategory\ContentCategorys;
use Doraemon\service\IntelligentRecommend\HaveRecommend;
use Frieza\Modules\Position\Controllers\UserProfileListController;

//use Doraemon\tools\Area;


class BlankSelectController extends Controller
{

    const NOT_IN_HAPPY_ACTIVITY_SCORE = 65;

    const FINE_SCORE = 70; // 优秀

    const ORDINARY_SCORE = 60; //普通

    const NOT_FINE_SCORE = 5;//差

    const FINE_MSGCODE = 230;

    const ORDINARY_MSGCODE = 228;

    const NOT_FINE_MSGCODE = 227;

    const OBJ_TYPE = BlockType::TYPE_BLANK;

    const ES_BUSINESS = [
        "NOT_BUSINESS" => 0,
        "SOFT_BUSINESS" => 1,
        "HARD_BUSINESS" => 2
    ];
    const NORMAL_WORD = '/home/adm_rsync_dir/article_common_remark.txt';

    const RECOMMENDBLANK_NOT_POINT = '/home/adm_rsync_dir/recommendblank_not_point.txt';


    public function __construct(Request $request)
    {
        parent::__construct();

    }

    public function index(Request $request, Content $content)
    {
        Admin::script(
            <<<EOF
        $('input[type=radio][name=select_area]').on('ifChecked',function(){
            if(this.value == 1) {
                $("select.multiplearea").parent().parent().hide();
                $("select.province").parent().parent().show();
                $("select.city").parent().parent().show();
            }else {
                $("select.multiplearea").parent().parent().show();
                $("select.city").parent().parent().hide();
                $("select.province").parent().parent().hide();
            }
        });
        
        $('input[type=radio][name=is_audit_again]').on('ifChecked',function(){
            if(this.value == 0) {
                $("select.audit_time").parent().parent().hide();
            }else {
                $("select.audit_time").parent().parent().show();
        
            }
        });
        $('input[type=radio][name=select_area]:checked').trigger('ifChecked');
        
        console.log($('.Find-filter-group-label').val());
        
EOF
        );

        Admin::style('.column-title {width:15%;}');

        $url = $_SERVER["REQUEST_URI"];
        $data_url = explode('?', $url);
        $export_url = $data_url[1] ?: '';

        Admin::script($this->setScript());
        Admin::script($this->commentPopup());
        Admin::script($this->adminLike());
        Admin::script($this->adminCopy());
        $requestParams = $request->all();


        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $requestParams['page_size'] = $pageSize;
        $requestParams['page'] = $page;


        $object = new BlankSearch($requestParams);
        $solr_list = Schedule::getList($object);
        $blank_ids = $solr_list['rows'] ?: [];
        if ($requestParams['nick'] && $object->uid == 0) {
            $blank_ids = [];
        }
        $list = [];
        if ($blank_ids && is_array($blank_ids)) {
            $list = dbBlank::select("*", [
                "AND" => [
                    "bid" => $blank_ids,
                    "status" => [
                        dbBlank::STATUS_WAIT_CHECK,
                        dbBlank::STATUS_SUCCESS,
                    ]
                ],
                'ORDER' => ['publish_time' => 'DESC']
            ]);

            //按照aiticle_id 排序
            $info = sBlank::getBlanksForDynamic($blank_ids);
        }

        $total = $solr_list['total'];
        $userProfile = new UserProfileListController();

        //获取社区特征分类
        $community_categorys = [];
        $categorys = ContentCategory::getTypesByObjs($blank_ids);

        if ($categorys && is_array($categorys)) {
            foreach ($categorys as $category) {
                $community_categorys[$category['obj_id']] = $category['category'];
            }
        }
        //运营评论列表
        $admin_comments = [];
        $comments = AdminAccountOperate::getByObjIds($blank_ids, AdminAccountOperate::ACCOUNT_TYPE_COMMENT,
            self::OBJ_TYPE);
        if ($comments && is_array($comments)) {
            foreach ($comments as $comment) {
                $admin_comments[$comment['obj_id']] = (string)Admin::user()->find($comment['admin_id'])->name;
            }
        }
        //运营点赞列表
        $admin_likes = [];
        $likes = AdminAccountOperate::getByObjIds($blank_ids, AdminAccountOperate::ACCOUNT_TYPE_LIKE, self::OBJ_TYPE);
        if ($likes && is_array($likes)) {
            foreach ($likes as $like) {
                $admin_likes[$like['obj_id']] = (string)Admin::user()->find($like['admin_id'])->name;
            }
        }
        $extendMap = [];
        $extendInfo = ContentSignExtend::getExtendInfoByNoteIds($blank_ids);
        if ($extendInfo && is_array($extendInfo)) {
            foreach ($extendInfo as $value) {
                $extendMap[$value['obj_id']] = $value;
            }
        }

        if ($list && is_array($list)) {
            foreach ($list as &$val) {
                $val['admin_tag'] = array_filter(explode(",", $val['admin_tag'])) ?: [];
                if ($info[$val['bid']] && is_array($info[$val['bid']])) {

                    $val['like'] = $info[$val['bid']]['counter']['like'];
                    $val['favorite'] = $info[$val['bid']]['counter']['favorite'];
                    $val['comments'] = $info[$val['bid']]['counter']['comments'];
                    $val['read'] = $info[$val['bid']]['counter']['read'];
                    $val['nick'] = $info[$val['bid']]['user_info']['nick'];
                    $val['user_type'] = $userProfile->FormateType($info[$val['bid']]['user_info']['uid'],
                        $info[$val['bid']]['user_info']['type']);
                    $adm_info = $userProfile->FormateUserTag($info[$val['bid']]['user_info']['uid']);
                    $val['user_tag'] = $adm_info['user_tag'];
                    $val['quality'] = $adm_info['user_quality'];
                    $val['cover_img_url'] = $info[$val['bid']]['blank_info']['cover_pic_url'];
                    $val['list_cover_img'] = $info[$val['bid']]['blank_info']['list_cover_img'];
                    $val['category'] = (string)$community_categorys[$val['bid']];
                }


                if ($val['admin_score'] > 0 && $val['status'] == 1) {
                    $val['audit_status'] = 1;
                }
                if ($val['status'] == dbBlank::STATUS_WAIT_CHECK && $val['admin_score'] > 0) {
                    $val['audit_status'] = dbBlank::STATUS_WAIT_CHECK;
                }
                if ($val['status'] = dbBlank::STATUS_WAIT_CHECK && $val['admin_score'] == 0) {
                    $val['audit_status'] = 2;
                }
                $val['audit_status'] = FilterConfig::ARTICLE_STATUS[$val['audit_status']];
                //运营相关操作
                $val['admin_comment'] = (string)$admin_comments[$val['bid']];
                $val['admin_like'] = (string)$admin_likes[$val['bid']];
                $val['is_business'] = $extendMap[$val['bid']]['is_business'] ?: 0;
                $val['is_display_business'] = $extendMap[$val['bid']]['is_display_business'] ?: 0;
            }
        }

        $gridModel = new pGridDataModel($list, $total, [

            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $export_url) {
                $grid->paginate($gridModel->getPerPage());
                //筛选
                $grid->disableExport();
                $grid->tools(function ($tools) use ($export_url) {
                    $url = url('/admin/blank/select/exportNormarlData?' . $export_url);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="' . $url . '"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
</div>';
                    $tools->append($button);
                });
                //筛选
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        $filter->dropDown('Find', [
                            'blank_id' => '文章id',
                            'uid' => 'uid',
                            'nick' => '用户昵称',
                            'title' => "文章标题",
                            'op_title' => '运营精选标题',
                            'adm_remark' => '文章备注',
                            'admin_tag' => '文章标签'
                        ]);
                        $filter->equal('user_type', '用户身份')->checkbox(Member::$typeDesc);
                        $filter->equal('confirmed', '用户标识')->checkbox(FilterConfig::USER_TYPE);
                        $filter->equal('quality', '用户质量')->checkbox(FilterConfig::QUALITY);
                        $filter->equal('badge_name', '用户徽章')->checkbox(FilterConfig::BADGE_NAME);
                        $filter->equal('business', '商业')->radio(FilterConfig::BUSINESS);

                    });

                    $filter->column(1 / 2, function ($filter) {

                        $filter->equal('high_check', '高级筛选')->checkbox(FilterConfig::HIGH_CHECK);

                        $filter->equal('score', '分数')->checkbox(FilterConfig::SCORE);
                        $filter->between('release_time', '发布时间')->datetime();
                        $filter->between('user_update_time', '用户编辑时间')->datetime();
                        $filter->equal('tag_status', '标签状态')->radio(FilterConfig::TAG_STATUS);
                        $filter->equal('audit_status', '审核状态')->radio(FilterConfig::AUDIT_AGAIN)->default(0);
                        $filter->in('category', '分类')->multipleSelect(function () {
                            $categorys = ContentCategory::getDimensionCategorys();
                            $data = ['0' => '未打品类'];
                            foreach ($categorys as $category) {
                                $data[$category['category']] = $category['category'];
                            }
                            return $data;
                        });

                    });
                    //条件展开
                    $filter->expand();

                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->expandFilter();


                $grid->column("bid", 'id')->display(function () {
                    $display = [];
                    $display[] = '<a href="/admin/blank/select/audit/' . $this->bid . '?category=' . $this->category . '" target="_blank">' . $this->bid . '</a>';
                    return implode('<br/>', $display);
                });
                $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
                $grid->column('admin_comment', '额外信息')->display(function () {
                    if (empty($this->admin_comment)) {
                        $comment_btn = "<a href='javascript:;' class='btn btn-default addComment'  data-id='$this->bid' id='$this->bid'>运营评论</a>";
                    } else {
                        $comment_btn = "<a href='javascript:;' class='btn btn-success'  data-id='$this->bid' id='$this->bid'>$this->admin_comment 已评论</a>";
                    }
                    if (empty($this->admin_like)) {
                        $like_btn = "<a href='javascript:;' class='btn btn-default addLike'  data-id='$this->bid' id='like$this->bid'>运营点赞</a>";
                    } else {
                        $like_btn = "<a href='javascript:;' class='btn btn-success'  data-id='$this->bid' id='like$this->bid'>$this->admin_like 已点赞</a>";
                    }
                    if ($this->is_business) {
                        $businessBtn = "<a href='javascript:;' class='btn btn-success addBusiness'  data-id='$this->bid' id='business$this->bid'>软广</a>";
                    } else {
                        $businessBtn = "<a href='javascript:;' class='btn btn-default addBusiness'  data-id='$this->bid' id='business$this->bid'>软广</a>";
                    }
                    if ($this->is_display_business) {
                        $displayBusiness = "<a href='javascript:;' class='btn btn-success addDisplayBusiness'  data-id='$this->bid' id='display$this->bid'>硬广</a>";
                    } else {
                        $displayBusiness = "<a href='javascript:;' class='btn btn-default addDisplayBusiness'  data-id='$this->bid' id='display$this->bid'>硬广</a>";
                    }
                    $copy_btn = "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->bid' >复制链接</a>";
                    if (Admin::user()->isRole('partime.user')) {
                        return $comment_btn . "<br><br>" . $like_btn . "<br><br>" . $copy_btn;
                    }
                    if (Admin::user()->isRole('coc.business_create_op') || Admin::user()->isRole('coc.business_cooperate')) {
                        return $comment_btn . "<br><br>" . $like_btn . "<br><br>" . $copy_btn . "<br><br>" . $businessBtn . "<br><br>" . $displayBusiness;
                    }
                    return $comment_btn . "<br><br>" . $like_btn . "<br><br>" . $copy_btn . "<br><br>" . $businessBtn;
                })->width(150);
                $grid->column('admin_tag', '文章标签')->display(function () {
                    $options = '';
                    if ($this->admin_tag && is_array($this->admin_tag)) {
                        foreach ($this->admin_tag as $tag) {
                            $options = $options . '<button style="display:inline-block;margin:2px;" class="marktag btn btn-sm btn-primary" data-had="">' . $tag . '</button><br/>';
                        }
                    }
                    return $options;
                });
                $grid->column("title", '文章信息')->style("width:200px");
                $grid->column("list_cover_img", '双列展示图')->image();

                $grid->column("interact", '交互')->display(function () {
                    $display = [];
                    $display[] = "<sapn style='font-size: 15px'>点赞:<b>" . $this->like
                        . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>收藏:<b>" . $this->favorite . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>评论:<b>" . $this->comments . "</b></sapn>";

                    return implode('<br/>', $display);
                })->width(100);

                $grid->column('publish_time', '首发时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->publish_time);
                });
                $grid->column('user_update_time', '用户编辑时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->edittime);
                });
                $grid->column('admin_score', '分数')->display(function () {
                    $display[] = '<p style="white-space:nowrap">' . FilterConfig::SCORE_CONTENT[$this->admin_score] . $this->admin_score . '</p>';

                    if (Admin::user()->can('article-Audit-D')) {
                        if ($this->admin_score > 70) {
                            //                           $display[] = '<a class="	delbest label  label-default" data-id="' . $this->bid . '"  href="javascript:void(0);">取消精选</a>';
                            $url = '/admin/blank/select/delBestFrom/' . $this->bid;
                            $display[] = '<a href="javascript:layer.open({
                                type: 2,
                                title: \'取消精选\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $url . '\'
                            });"    data-score="80" class="label  grade_2 label-info"> 取消精选  </a><br/>';
                        } else {
                            $display[] = '<a class=" addbest label  label-success" data-id="' . $this->bid . '"  href="javascript:void(0);">设置精选</a>';
                        }
                    }
                    return implode('<br/>', $display);


                })->width(200);;

                $grid->column('audit_status', '审核')->display(function ($title, Grid\Column $column) {
                    if ($this->audit_status == '已审核') {
                        return $column->label('success');
                    } else {
                        if ($this->audit_status == '未审核') {
                            return $column->label('warning');
                        } else {
                            if ($this->audit_status == '待复审') {
                                return $column->label('danger');
                            }
                        }
                    }
                });

                $grid->column('category', '分类')->display(function () {
                    $category = $this->category;
                    $options = '';
                    if (!empty($category)) {
                        $options = $options . "<button style='display:inline-block;margin:2px;' class='community_category btn btn-sm marktag btn-success' data-type='5' 
data-dimension='1' data-id='$this->bid' data-category='" . $category . "' >" . $category . "</button>&nbsp;";
                    }
                    return $options;
                })->width(200);

                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $url = 'http://m.haohaozhu.cn/blank/' . $actions->row->bid . '.html?preview=1';
                    $actions->prepend('<p style="white-space:nowrap"><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });">预览  </a></p>');

                    if (Admin::user()->can('article-Audit-C')) {
                        $actions->prepend('<p><a class="	del label  label-info" data-id="' . $actions->row->bid . '"  href="javascript:void(0);">删除</a></p>');

                        $url = '/admin/blank/select/privateFrom/' . $actions->row->bid;
                        $html = '<p><a href="javascript:layer.open({
                                type: 2,
                                title: \'仅自己可见\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $url . '\'
                            });"    data-score="80" class="label  grade_2 label-info"> 仅自己可见  </a><p/>';

                        $actions->prepend($html);
                    }
                });

            });


        $tab = new Tab();
        $tab->add('文章列表', $gridList->render());


        $tab->addLink('违规文章', url('/admin/blank/select/draftlist'));

        $content->row($tab);

        return $content
            ->header('文章')
            ->description(' ')
            ->breadcrumb(
                ['text' => '文章列表', 'url' => '/blank/select/index']
            );
    }


    /*draft article
     *
     * */
    public function draftlist(Request $request, Content $content)
    {
        Admin::script(
            <<<EOF
              //仅自己可见
         $('.recoverPrivateOfBlank').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要恢复全局可见么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/blank/select/recoverPrivateOfBlank/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
        
EOF
        );

        $requestParams = $request->all();

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        if ($requestParams['Find']) {
            $requestParams[FilterConfig::BLANK_FIND_GROUP[$requestParams['Find_group']]] = $requestParams['Find'];
        }

        $map = ['ORDER' => ['addtime' => 'DESC']];
        if ($requestParams['nick']) {
            $uid = Member::getUidByNick($requestParams['nick']);
            if ($uid) {
                $map['AND']['uid'] = $uid;
            }
        }
        if ($requestParams['uid']) {
            $map['AND']['uid'] = $requestParams['uid'];
        }
        if ($requestParams['blank_id']) {
            $map['AND']['bid'] = $requestParams['blank_id'];
        }
        if ($requestParams['title']) {
            $map['AND']['title[~]'] = $requestParams['title'];
        }
        if ($requestParams['adm_remark']) {
            $map['AND']['adm_remark[~]'] = $requestParams['adm_remark'];
        }

        if ($requestParams['addtime']['start'] && $requestParams['addtime']['end']) {
            $map['AND']['addtime[<>]'] = [
                strtotime($requestParams['addtime']['start']),
                strtotime($requestParams['addtime']['end'])
            ];
        }
        $status = [
            dbBlank::STATUS_PRIVATE,
            dbBlank::STATUS_DELETE,
            dbBlank::STATUS_DRAFT,
            dbBlank::STATUS_FIRST_EDIT,
            dbBlank::STATUS_FORCE_OUT,
        ];
        if ($requestParams['status']) {
            //草稿
            if ($requestParams['status'] == 1) {
                $status = [
                    dbBlank::STATUS_DRAFT,
                    dbBlank::STATUS_FIRST_EDIT,
                ];
            }
            //封杀
            if ($requestParams['status'] == 2) {
                $status = [
                    dbBlank::STATUS_FORCE_OUT,
                ];
            }

            //删除
            if ($requestParams['status'] == 3) {
                $status = [
                    dbBlank::STATUS_DELETE,
                ];
            }
            //仅自己可见
            if ($requestParams['status'] == 4) {
                $status = [
                    dbBlank::STATUS_PRIVATE,
                ];
            }
        }
        $map['AND']['status'] = $status;
        $total = dbBlank::count($map);
        $map['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = dbBlank::select("*", $map);
        if ($list && is_array($list)) {
            $uids = array_column($list, 'uid');
            $user_info = sMember::getUserInfoByUserIds($uids);
            foreach ($list as &$val) {
                $val['nick'] = $user_info[$val['uid']]['nick'];
            }
        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $export_url = '';
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $export_url) {
                $grid->paginate($gridModel->getPerPage());
                //筛选
                $grid->disableExport();
                //筛选
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->group('Find', function ($group) {
                        $group->equal('文章id');
                        $group->equal('uid');
                        $group->equal('用户昵称');
                        $group->equal("文章标题");
                        $group->equal("文章备注");

                    });
                    $filter->equal('status', '文章状态')->radio(FilterConfig::STATUS_NONORMAL)->default(0);
                    $filter->between('addtime', '创建时间')->datetime();
                    //条件展开
                    $filter->expand();
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->expandFilter();
                $grid->fixColumns(0, -4);
                $grid->column("bid", 'id')->display(function () {
                    $display = [];
                    $display[] = '<a href="/admin/blank/select/audit/' . $this->bid . '" target="_blank">' . $this->bid . '</a>';
                    $display[] = "<sapn style='font-size: 15px'>uid:<b>" . $this->uid . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>昵称:<b>" . $this->nick . "</b></sapn>";
                    return implode('<br/>', $display);
                });
                $grid->column("title", '文章信息')->display(function () {
                    $display = [];
                    $display[] = "<sapn style='font-size: 15px'>标题:<b>" . $this->title . "</b></sapn>";
                    if ($this->publish_time) {
                        $display[] = "<sapn style='font-size: 15px'>发布时间:<b>" . date('Y-m-d H:i:s',
                                $this->publish_time) . "</b></sapn>";

                    }
                    if ($this->adm_remark) {
                        $display[] = "<sapn style='font-size: 15px'>备注:<b>" . $this->adm_remark . "</b></sapn>";
                    }
                    return implode('<br/>', $display);
                });

                $grid->column('status', '状态')->display(function ($title, Grid\Column $column) {
                    $display = [];
                    if ($this->status == dbBlank::STATUS_DRAFT || $this->status == dbBlank::STATUS_FIRST_EDIT) {

                        $display[] = '<a class=" label  label-default" data-id="' . $this->bid . '"  href="javascript:void(0);">草稿</a>';
                    } elseif ($this->status == dbBlank::STATUS_FORCE_OUT) {
                        $display[] = '<a class=" label  label-danger" data-id="' . $this->bid . '"  href="javascript:void(0);">后台删除</a>';

                    } elseif ($this->status == dbBlank::STATUS_DELETE) {
                        $display[] = '<a class=" label  label-info" data-id="' . $this->bid . '"  href="javascript:void(0);">删除</a>';

                    } elseif ($this->status == dbBlank::STATUS_PRIVATE) {
                        $display[] = '<a class=" label  label-success" data-id="' . $this->bid . '"  href="javascript:void(0);">仅自己可见</a>';
                    }
                    return implode("<br/>", $display);


                });

                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        //  return Admin::user()->find($this->admin_id)->name;
                    }
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $url = 'http://m.haohaozhu.cn/blank/' . $actions->row->bid . '.html?preview=1';
                    $actions->prepend('<p style="white-space:nowrap"><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });">预览  </a></p>');

                    if ($actions->row->status == dbBlank::STATUS_PRIVATE) {
                        $actions->prepend('<a class="fa fa-adjust recoverPrivateOfBlank" data-id="' . $actions->row->bid . '"  href="javascript:void(0);">设置全部可见  </a>');

                    }
                });
            });

        $tab = new Tab();
        $tab->addLink('文章列表', url('/admin/blank/select/index'));

        $tab->add('违规文章', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('文章')
            ->description(' ')
            ->breadcrumb(
                ['text' => '文章列表', 'url' => '/blank/select/index']
            );
    }


    /**
     * 审核
     */
    public function audit(Request $request, Content $content, $bid)
    {

        Admin::style('.content-wrapper {margin-left:0px;}');
        Admin::style('.main-sidebar {display:none;}');
        Admin::style('.main-header {display:none;}');
        Admin::style('.form-horizontal {margin-left:-20%;}');
        Admin::script(
            <<<EOF
          //使用常用语
           $('.normalword').on('change',function(){
            var option = $(this).val();
            var remark=  $(".remark").val()
            $(".remark").val(remark+option);       
         });
         //一键复审
         $('.reCheck').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定一键复审么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/blank/select/reCheck/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
EOF
        );
        $category = $request->get('category');
        return $content
            ->header('文章审核')
            ->breadcrumb(
                ['text' => "审核"]
            )
            ->row(function (Row $row) use ($bid, $category) {
                $row->column(9, $this->H5($bid));
                $row->column(3, $this->auditForm($bid, $category));
            });
    }


    public function H5($bid)
    {
        $form = new Form();
        $form->disableReset();
        $form->disableSubmit();
        $url = 'https://m.haohaozhu.cn/blank/' . $bid . '.html?preview=1';
        $form->html('<iframe src="' . $url . '" style="width:100%; height:1000px;margin-top:10px;"></iframe>');

        return $form->render();
    }

    public function auditForm($bid, $cate)
    {
        Admin::script($this->setScript());
        $info = dbBlank::getBlank($bid);
        if ($info['status'] == dbBlank::STATUS_DRAFT || $info['status'] == dbBlank::STATUS_FIRST_EDIT) {
            $form = new  Form();
            $form->disableReset();
            $form->disableSubmit();
            return $form->render();
        };
        $word = self::getNormalWord();
        if ($info && is_array($info)) {
            $info['tags'] = array_filter(explode(",", trim($info['admin_tag']))) ?: [];
            $info['op_status'] = $info['status'];
            $info['remark'] = $info['adm_remark'];
            $info['category'] = $cate ?: 'selector';
        }
        $tags = explode("\n", file_get_contents('/home/adm_rsync_dir/tags/adm_tags_all'));
        if ($tags && is_array($tags)) {
            $tags = array_combine($tags, $tags);
        }

        $form = new Form($info);

        if (Admin::user()->can('article-Audit-D')) {
            if ($info['admin_score'] > 70) {
                $url = '/admin/blank/select/delBestFrom/' . $bid;
                $form->html('<a href="javascript:layer.open({
                                type: 2,
                                title: \'取消精选\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $url . '\'
                            });"    data-score="80" class="label  grade_2 label-info"> 取消精选  </a><br/>');
            } else {
                $form->html('<a class=" addbest label  label-success" data-id="' . $bid . '"  href="javascript:void(0);">设置精选</a>');
            }
        }
        if (Admin::user()->can('article-Audit-A') && $info['status'] == dbBlank::STATUS_WAIT_CHECK && $info['admin_score'] > 0) {
            $form->html('<a href="javascript:void(0)" data-id="' . $info['bid'] . '" class="label label-info reCheck">一键复审</a>');
        }

        $form->hidden('bid');
        if (Admin::user()->can('article-Audit-B')) {
            $form->multipleSelect("tags", '标签')->options($tags)->load('tag', route("Blank.tag"));
        }
        if (Admin::user()->can('article-Audit-A')) {
            if ($info['admin_score'] <= 70) {
                $form->fieldChange('admin_score', '打分', $form)
                    ->options([
                        '0' => '未打分',
                        '5' => '差',
                        '60' => '普通',
                        '70' => "优秀",
                    ])
                    ->default(0)
                    ->callablePreCommon(function (Form $form) {
                    })->callableMap([
                        0 => function (Form $form) {
                        },
                        5 => function (Form $form) {
                        },
                        60 => function (Form $form) {
                        },
                        70 => function (Form $form) {
                        },
                    ]);
            } else {
                $form->html('<span>精选文章<span/>', '分数');
            }

        }

        $form->textarea('remark', "备注");
        $form->select('normalword', '备注常用语')->options($word)->default('-1')->help('选择备注常用语后，输入的备注将无效');
        $categorys = ContentCategory::getDimensionCategorys();
        $data['selector'] = '请选择';
        foreach ($categorys as $category) {
            $data[$category['category']] = $category['category'];
        }
        $form->select('category', '类别')->options($data);
        $form->action('/admin/blank/select/audit/save');
        $form->disableReset();
        return $form->render();
    }


    /*获取常用语
     *
     * */
    public static function getNormalWord()
    {
        $result = [
            '-1' => '选择常用语',
        ];
        $word = array_map('trim', explode("\n", file_get_contents('/home/adm_rsync_dir/article_common_remark.txt')));
        foreach ($word as $key => $value) {
            $result[$value] = $value;
        }
        return $result;
    }


    /*保存审核内容
     *
     * */
    public static function auditSave(Request $request)
    {

        try {
            $request = $request->all();
            $bid = $request['bid'];
            $info = dbBlank::getBlank($bid);
            if (empty($info)) {
                throw new \Exception('文章不存在！');
            }
            $score = $request['admin_score'] ?: 0;
            $remark = $request['remark'] ?: '';
            $category = $request['category'] ?: '';
            $tags = [];
            if (isset($request['tags'])) {
                $tags = array_unique(array_filter($request['tags'])) ?: [];
            }

            $admin_tag = '';
            if ($tags && is_array($tags)) {
                $admin_tag = implode(",", $tags);
            }
            $update_data = [];
            if ($score) {
                $update_data['admin_score'] = $score;
                $update_data  ['status'] = dbBlank::STATUS_SUCCESS;
                $update_data  ['check_time'] = time();
            }
            if ($remark) {
                $update_data['adm_remark'] = $remark;
            }
            if ($admin_tag) {
                $update_data['admin_tag'] = $admin_tag;
            }
            $update_data['admin_id'] = Admin::user()->id;

            $rs = dbBlank::updateById($bid, $update_data);
            // 进行分类操作
            $type = ContentCategorys::obj_type_blank;
            $dimensionId = ContentCategorys::DIMENSION_THEME;
            $oldCategory = ContentCategorys::getCategory($bid, $dimensionId);
            $data["category"] = $category == 'selector' ? '' : $category;
            $data['admin_id'] = Admin::user()->id;
            $date = date('Y-m-d H:i:s', time());
            if ($oldCategory) {
                $data["edittime"] = $date;
                $conditions = ['obj_id' => $bid, 'dimension_id' => $dimensionId];
                ContentCategory::editCategorys($conditions, $data);
            } else {
                $data["obj_id"] = $bid;
                $data['obj_type'] = $type;
                $data["addtime"] = $date;
                ContentCategory::addCategorys($data);
            }
            //审核
            if ($rs) {
                Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $bid]);
                $aQueueData = ["blank_id" => $bid];
                Queue::insertQueue('Blank/updateSolr', $aQueueData);

                if ($score > 10) {
                    //如果打分高于10分，投wiki队列
                    \Doraemon\amqp\Queue::insertQueue('queue/wiki/afterAuditContent', [
                        'obj_id' => $bid,
                    ], \Doraemon\amqp\Queue::QUEUE_BIZ);
                }

                $success = new MessageBag([
                    'title' => '操作成功'
                ]);

                //发送审核消息
                return redirect('/admin/blank/select/audit/' . $bid . '?category=' . $category)->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return redirect('/admin/blank/select/audit/' . $bid . '?category=' . $category)->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return redirect('/admin/blank/select/audit/' . $bid . '?category=' . $category)->with(compact('error'));
        }


    }
//
//    /**
//     * @deprecated 删除空白
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function area(Request $request)
//    {
//        $pid = $request->input('q', 0);
//        $areas = Area::getLocation($pid);
//        $format = array_map(function ($k, $v) {
//            return [
//                'id' => $k,
//                'text' => $v,
//            ];
//        }, array_keys($areas), $areas);
//        return response()->json($format);
//    }


    /*精选框
     *
     * */
    public function privateFrom(Request $request, Content $content, $bid)
    {
        Admin::style('.main-header {display:none;}');
        $info = dbBlank::getBlank($bid);
        if ($info['status'] == dbBlank::STATUS_PRIVATE) {
            $info['msg'] = "已设置为仅自己可见";
        }
        $form = new Form($info);
        $form->hidden('bid');
        if ($info['status'] == dbBlank::STATUS_PRIVATE) {
            $form->display("msg", '状态')->disable();
            $form->disableReset();
            $form->disableSubmit();

        } else {
            $form->fieldChange('is_send_msg', '是否下发消息', $form)
                ->options([0 => '不发消息', 1 => '发消息'])
                ->default(0)
                ->callablePreCommon(function (Form $form) {
                })->callableMap([
                    0 => function (Form $form) {
                    },
                    1 => function (Form $form) {
                        $form->textarea('msg', '下行信息');
                    },

                ]);
            $form->disableReset();
            $form->action('/admin/blank/select/setPrivate');
        }
        return $content->row($form->render());
    }

    /*添加精选
     *
     * */
    public function addBest(Request $request, $bid)
    {
        $info = dbBlank::getBlank($bid);
        //是否下发积分
        if ($info['admin_score'] <= 80) {
            $event_name = PointConfig::POINT_TYPE_GREAT_BLANK;
            $point = 2000;
            $source = 'admin';
            $request_id = $source . $event_name . $bid . date('YmdHis', time());
            $msg['obj_id'] = $bid;
            $msg['detail'] = "文章加编辑精选";
            $ext_info = json_encode($msg, JSON_UNESCAPED_UNICODE);
            PointClient::awardPoint(IdParse::getUid($bid), $point, $event_name, $request_id, $source, $ext_info);
            //发积分后查文件中是否有这个bid,有则删除
            if (file_exists(self::RECOMMENDBLANK_NOT_POINT)) {
                $bids = file(self::RECOMMENDBLANK_NOT_POINT, FILE_IGNORE_NEW_LINES);
                if (in_array($bid, $bids)) {
                    foreach ($bids as $k => $v) {
                        if ($bid == $v) {
                            unset($bids[$k]);
                        }
                    }
                    $bids = array_values($bids);
                    //重新将数据写入文件
                    file_put_contents(self::RECOMMENDBLANK_NOT_POINT, '');
                    foreach ($bids as $v) {
                        file_put_contents(self::RECOMMENDBLANK_NOT_POINT, $v . "\n", FILE_APPEND);
                    }
                }
            }
            //发消息
            Queue::insertQueue('queue/Sysmsg/Send',
                [
                    'msgCode' => 122,
                    'to_uid' => IdParse::getUid($bid),
                    'msgParams' => [
                        'blank_id' => $bid,
                        'link' => HhzNiceLivingUrl::getBlankDetailLink($bid),

                    ]
                ], Queue::QUEUE_DORAEMON
            );
        }
        //想库里添加数据
        $update_data = [
            'admin_score' => 80,
            'status' => dbBlank::STATUS_SUCCESS,
            'admin_id' => Admin::user()->id,
            'check_time' => time(),
        ];
        $rs = dbBlank::updateById($bid, $update_data);
        if ($rs) {
            Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $bid]);
            $aQueueData = ["blank_id" => $bid];
            Queue::insertQueue('Blank/updateSolr', $aQueueData);

            $status = true;
            $message = "操作成功";

        } else {
            $status = false;
            $message = "操作失败";
        }
        return response()->json(compact('status', 'message'));
    }


    /*精选框
   *
   * */
    public function delBestFrom(Request $request, Content $content, $bid)
    {
        Admin::style('.main-header {display:none;}');
        $info = dbBlank::getBlank($bid);
        if ($info['admin_score'] <= 70) {
            $info['msg'] = "已取消编辑精选";
        }
        $form = new Form($info);
        $form->hidden('bid');
        if ($info['admin_score'] <= 70) {
            $form->display("msg", '状态')->disable();
            $form->disableReset();
            $form->disableSubmit();

        } else {
            $form->fieldChange('is_send_msg', '是否下发消息', $form)
                ->options([0 => '不发消息', 1 => '发消息'])
                ->default(0)
                ->callablePreCommon(function (Form $form) {
                })->callableMap([
                    0 => function (Form $form) {
                    },
                    1 => function (Form $form) {
                        $form->textarea('msg', '下行信息');
                    },

                ]);
            $form->disableReset();
            $form->action('/admin/blank/select/delBest');
        }
        return $content->row($form->render());
    }


    /*删除精选
     * */
    public function delBest(Request $request)
    {
        try {
            $request = $request->all();

            $bid = $request['bid'];
            $send_msg = $request['msg'];
            $is_send_msg = $request['is_send_msg'] ?: 0;
            //删除精选
            $info = dbBlank::getBlank($bid);
            if (empty($info)) {
                throw new \Exception('文章不存在！');
            }

            if (file_exists(self::RECOMMENDBLANK_NOT_POINT)) {
                $bids = file(self::RECOMMENDBLANK_NOT_POINT, FILE_IGNORE_NEW_LINES);
            }
            if (!in_array($bid, $bids)) {
                //扣除积分逻辑
                $uid = $info['uid'];
                $event_name = PointConfig::POINT_TYPE_UNGREAT_BLANK;
                $point = '2000';
                $source = 'admin';
                $request_id = $source . $event_name . $bid . date('YmdHis', time());
                $msg['obj_id'] = $bid;
                $msg['detail'] = "经验文章取消编辑精选";
                $ext_info = json_encode($msg, JSON_UNESCAPED_UNICODE);
                PointClient::deductPoint($uid, $point, $event_name, $request_id, $source, $ext_info);
            }
            //更新文章分数
            $update_data = [
                'admin_score' => 70,
                'status' => dbBlank::STATUS_SUCCESS,
                'admin_id' => Admin::user()->id,
                'check_time' => time(),
            ];
            $rs = dbBlank::updateById($bid, $update_data);
            if ($rs) {
                Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $bid]);
                $aQueueData = ["blank_id" => $bid];
                Queue::insertQueue('Blank/updateSolr', $aQueueData);
                if ($is_send_msg && $send_msg) {
                    $message_data = [
                        'msgCode' => 0,
                        'to_uid' => IdParse::getUid($bid),
                        'msgParams' => [
                            'from_uid' => \Doraemon\service\User::DEFAULT_HAOHAOZHU_UID,
                            'detail' => $send_msg,
                            'link' => HhzNiceLivingUrl::getBlankDetailLink($bid)
                        ]
                    ];
                    Queue::insertQueue('queue/Sysmsg/Send', $message_data, Queue::QUEUE_DORAEMON);
                }
                $status = true;
                $message = "操作成功";
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/blank/select/delBestFrom/' . $bid)->with(compact('success'));
    }


    /*仅自己可见
     * */
    public function setPrivate(Request $request)
    {

        try {
            $request = $request->all();

            $bid = $request['bid'];
            $msg = $request['msg'];
            $is_send_msg = $request['is_send_msg'] ?: 0;

            //删除精选
            $info = dbBlank::getAllBlanks($bid);
            if (empty($info)) {
                throw new \Exception('文章不存在！');
            }
            $rs = dbBlank::updateById($bid,
                ['status' => dbBlank::STATUS_PRIVATE, 'admin_score' => 4, 'admin_id' => Admin::user()->id]);

            $upData['status'] = dbBlank::STATUS_PRIVATE;
            MyArticleList::updateByObjId($bid, ['status' => MyArticleList::STATUS_PRIVATE]);

            // 删除正在发生
            Queue::insertQueue('Api/delFeedByObjId', [
                'obj_id' => $bid
            ]);

            //图片设置为仅自己可见
            if ($rs) {
                Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $bid]);
                $aQueueData = ["blank_id" => $bid];
                Queue::insertQueue('Blank/updateSolr', $aQueueData);
                if ($msg && $is_send_msg) {
                    $message_data = [
                        'msgCode' => 0,
                        'to_uid' => IdParse::getUid($bid),
                        'msgParams' => [
                            'from_uid' => \Doraemon\service\User::DEFAULT_HAOHAOZHU_UID,
                            'detail' => $msg,
                            'link' => HhzNiceLivingUrl::getBlankDetailLink($bid),
                        ]
                    ];
                    Queue::insertQueue('queue/Sysmsg/Send', $message_data, Queue::QUEUE_DORAEMON);
                }
                $status = true;
                $message = '操作成功';
            } else {
                $status = false;
                $message = '操作失败';
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/blank/select/privateFrom/' . $bid)->with(compact('success'));
        // return  response()->json(compact('status', 'message'));
    }

    /*恢复全体可见
     *
     * */
    public function recoverPrivateOfBlank(Request $request, $bid)
    {
        try {
            $info = dbBlank::getAllBlanks($bid);
            if (!$info && !is_array($info)) {
                throw new \Exception("The article isn't existent");
            }
            $article_data = [];
            $article_data['edittime'] = time();
            $article_data['admin_score'] = 0;
            $article_data['status'] = dbBlank::STATUS_SUCCESS;
            dbBlank::updateById($bid, $article_data);

            $upData['status'] = 1;
            MyArticleList::updateByObjId($bid, $upData);

            //添加到队列，更新搜索图片
            // 删除文章信息缓存
            $aQueueData = ["blank_id" => $bid];
            Queue::insertQueue('Blank/updateSolr', $aQueueData);
            Queue::insertQueue('TotalArticle/updateTotalArticle', [
                'article_id' => $bid
            ]);
            $status = true;
            $message = '操作成功';
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));
    }

    /*删除
     * */
    public function del(Request $request, $bid)
    {
        try {
            $info = dbBlank::getBlank($bid);
            if (empty($info)) {
                throw new \Exception('文章不存在！');
            }
            //绑定设计师计数

            $rs = dbBlank::updateById($bid, ['status' => dbBlank::STATUS_DELETE, 'admin_id' => Admin::user()->id]);
            if (empty($rs)) {
                throw new \Exception('Article表操作失');
            }
            //myarticle
            $article_list = MyArticleList::getInfoByObjId($bid);
            if ($article_list) {
                $rs = MyArticleList::updateByObjId($bid, ['status' => MyArticleList::STATUS_DELETE]);
                if (empty($rs)) {
                    throw new \Exception('MyArticleList表操作失败');
                }
            }
            //recommend article
            if ($info['is_del_points'] == 0) {
                //扣除积分
                $uid = IdParse::getUid($bid);
                $event_name = PointConfig::POINT_TYPE_UNGREAT_BLANK;
                $point = '5000';
                $source = 'admin';
                $request_id = $source . $event_name . $bid . date('YmdHis', time());
                $msg['obj_id'] = $bid;
                $msg['detail'] = "文章删除导致取消编辑精选";
                $ext_info = json_encode($msg, JSON_UNESCAPED_UNICODE);
                PointClient::deductPoint($uid, $point, $event_name, $request_id, $source, $ext_info);
            }

            if ($rs) {
                $uid = IdParse::getUid($bid);
                \Biz\service\wiki\ObjRelateWiki::delBlankRelate($uid, $bid);
                Queue::insertQueue("TotalArticle/delArticleById", ['article_id' => $bid]);
                $aQueueData = ["blank_id" => $bid];
                Queue::insertQueue('Blank/updateSolr', $aQueueData);

                $status = true;
                $message = "操作成功";
            } else {
                $status = false;
                $message = "操作失败";
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));
    }

    /*一键复审
     *
     * */
    public function reCheck(Request $request, $bid)
    {
        try {
            if (empty($bid)) {
                throw new \Exception('文章ID传入失败！');
            }
            $rs = dbBlank::updateById($bid,
                ['status' => dbBlank::STATUS_SUCCESS, 'admin_id' => Admin::user()->id, 'check_time' => time()]);
            if ($rs) {
                Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $bid]);
                $aQueueData = ["blank_id" => $bid];
                Queue::insertQueue('Blank/updateSolr', $aQueueData);
                $status = true;
                $message = "操作成功";
            } else {
                $status = false;
                $message = "操作失败";
            }

        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));

    }


    /**
     * 常用语编辑
     */
    public function editNormalWord(Content $content)
    {
        $tab = new Tab();
        $tab->addLink('文章列表', url('/admin/blank/select/index'));
        $tab->addLink('违规文章', url('/admin/blank/select/draftlist'));
        $tab->add("编辑常用语", $this->editNormalWordAction(), true);

        return $content
            ->header('反馈管理')
            ->breadcrumb(
                ['text' => "常用语编辑"]
            )
            ->body($tab);
    }

    /**
     * 常用语编辑--信息展示
     */
    private function editNormalWordAction()
    {
        $info = $this->NormalWord();
        $form = new Form($info);
        $form->textarea('text', '常用语')->help('请用换行隔开每条常用语');
        $form->action('/admin/blank/select/normalword/list/save');
        return $form->render();
    }

    /**
     * 常用语编辑--信息保存
     */
    public function saveNormalWord(Request $request)
    {
        $text = $request->input('text', '');
        $result = $this->NormalWord($text);

        if ($result) {
            return back()->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } else {
            return back()->with('error', new MessageBag([
                'title' => '操作失败'
            ]));
        }

    }

    /*Normarl word
     *
     * */
    public function NormalWord($text = null)
    {
        if ($text) {
            $rs = file_put_contents(self::NORMAL_WORD, $text);
            if ($rs) {
                return true;
            } else {
                return false;
            }
        } else {
            $word = file_get_contents(self::NORMAL_WORD);
            return [
                'text' => $word,
            ];
        }
    }

    /*导出数据
     *
     * */
    public function exportNormarlData(Request $request)
    {
        $request = $request->all();

        $pageSize = 1500;
        $page = 1;
        if (isset($request['Find_group']) && $request['Find']) {
            $request[FilterConfig::BLANK_FIND_GROUP[$request['Find_group']]] = $request['Find'];
        }
        $request['page_size'] = $pageSize;
        $request['page'] = $page;
        $object = new BlankSearch($request);
        $solr_list = Schedule::getList($object);
        $blank_ids = $solr_list['rows'] ?: [];
        $list = [];
        if ($blank_ids && is_array($blank_ids)) {
            $list = dbBlank::select("*", [
                "AND" => [
                    "bid" => $blank_ids,
                    "status" => [
                        dbBlank::STATUS_WAIT_CHECK,
                        dbBlank::STATUS_SUCCESS,
                    ]
                ],
            ]);
            $list = array_combine(array_column($list, 'bid'), $list);
            $info = sBlank::getBlanksForDynamic($blank_ids);
        }
        $row = $this->formateArticleInfo($info, $list);
        if (!empty($row)) {
            $subject['list'] = $row;
            $subject['total'] = count($row);
        } else {
            $subject['list'] = [];
            $subject['total'] = 0;
        }
        $reason = '文章信息';
        $header = ['bid', 'uid', '昵称', '用户身份', '阅读', '点赞', '评论', '收藏', '发布时间', '质量'];
        $letter = range('A', 'M');
        $excelObj = new DownExcel();
        $excelObj->setFileName($reason);
        $excelObj->setSheetTitle($reason);

        //设置列宽
        $widths = ['A' => 45, 'B' => 100];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $excelObj->create($subject['list'], $header);
    }


    /*format article info
     * */
    public function formateArticleInfo($article_info, $hash_list_info)
    {
        $list = [];
        $UserProfileList = new UserProfileListController();
        if ($article_info && is_array($article_info)) {
            foreach ($article_info as $info) {
                $list[] = [
                    'bid' => $info['blank_info']['bid'],
                    'uid' => $info['user_info']['uid'],
                    'nick' => $info['user_info']['nick'],
                    'user_type' => $UserProfileList->FormateType($info['user_info']['uid'], $info['user_info']['type']),
                    //  'title' => $info['blank_info']['title'],
                    'read' => $info['counter']['read'] ?: 0,
                    'like' => $info['counter']['like'] ?: 0,
                    'comments' => $info['counter']['comments'] ?: 0,
                    'fav' => $info['counter']['favorite'] ?: 0,
                    'publish_time' => date("Y-m-d H:i:s", $info['blank_info']['publish_time']),
                    'score' => $hash_list_info[$info['blank_info']['bid']]['admin_score'] ? FilterConfig::SCORE_CONTENT[$hash_list_info[$info['blank_info']['bid']]['admin_score']] : "未打分"

                ];

            }

        }
        return $list;

    }

    /*设置scirpt
     *
     * */
    private function setScript()
    {
        return <<<SCRIPT
       
       $('.delbest').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要取消精选么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/blank/select/delBest/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
        
        //设置精选
         $('.addbest').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要设置精选么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/blank/select/addBest/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
//        //仅自己可见
//         $('.setPrivate').unbind('click').click(function(){
//            var id= $(this).data('id');
//            layer.confirm('确定要设置仅自己可见么？', {
//                btn: ['确定', '取消']
//            }, function (index) {
//                layer.close(index);
//                 let url = '/admin/blank/select/privateFrom/'+ id;
//                let params = {};
//                $.post(url, params , function (result) {
//                    if (result.status == 1) {
//                        layer.msg(result.message);
//                        setTimeout(function () {
//                            parent.window.location.reload();
//                        }, 2000);
//                    } else {
//                        layer.msg(result.message);
//                    }
//                });
//            });
//        })
        //删除
         $('.del').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/blank/select/del/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
SCRIPT;
    }


    public function searchTag(Request $request)
    {
        return [];
    }

    //评论弹窗
    public function commentPopup()
    {
        return <<<SCRIPT
           
            $('.addComment').unbind('click').click(function() {
                var id = $(this).data('id');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '运营评论',
                    shadeClose: true,
                    shade: 0.4,
                    maxmin: true,
                    area: ['700px', '600px'],
                    content: 'comment/'+id,
                    end: function () {
                        $.ajax({type:"get",url:"comment/check/"+id,success:function(data){
                      
                            if(data != '') {
                                $('#'+id).html(data+"已评论");
                                $('#'+id).addClass('btn-success');
                                $('#'+id).css('color','#FFFFFF');
                                $('#'+id).attr('disabled', 'disabled');
                            }
                        }});
                    }
                });
		    });
SCRIPT;
    }

    public function checkComment(Request $request, $note_id)
    {
        $rs = '';
        $hasComment = AdminAccountOperate::getByObjId($note_id, AdminAccountOperate::ACCOUNT_TYPE_COMMENT,
            self::OBJ_TYPE);
        if ($hasComment && is_array($hasComment)) {
            $rs = (string)Admin::user()->find($hasComment['admin_id'])->name;
        }
        return $rs;
    }

    //添加评论弹窗
    public function addCommentPop(Request $request, \App\Admin\Extensions\WorkContent $content, $id)
    {
        $request = $request->all();
        return $content
            ->header('运营评论')
            ->body(self::addCommentAction($request, $id));
    }

    public function addCommentAction($request, $id)
    {
        $data = [
            'obj_id' => $id,
            'content' => ''
        ];
        $account = [];
        $accounts = AdminAccount::getByAdminId(Admin::user()->id);
        if ($accounts && is_array($accounts)) {
            $user_infos = Member::getUsers($accounts);
            if ($user_infos && is_array($user_infos)) {
                foreach ($user_infos as $user_info) {
                    $account[$user_info['uid']] = $user_info['nick'];
                }
            }
        }
        $form = new Form($data);
        $form->display('obj_id', '内容id');
        $form->textarea('content', '评论内容')->setWidth(10, 2)->required('不能为空')->help('请输入内容内容');
        $form->select('account', '选择发布账号')->options($account)->required('必选');
        $form->html("<a href='" . $id . "/commentaccount' class='btn btn-small btn-sm'>账号管理</a>");
        $form->action('/admin/blank/select/comment/' . $id . '/save');

        return $form->render();
    }

    //添加评论
    public function saveComment(Request $request, $id)
    {
        $is_owner = 0;
        $request = $request->all();
        $obj_uid = dbBlank::getBlank($id)['uid'];
        if ($obj_uid == $request['account']) {
            $is_owner = 1;
        }
        $data = [
            "content" => trim($request['content']),
            "obj_id" => $id,
            "obj_type" => self::OBJ_TYPE,
            "type" => 1,
            "uid" => $request['account'],
            "to_uid" => 0,
            "addtime" => time(),
            "add_ip" => Ip::getClientIp(),
            "status" => 1,
            "admin_id" => Admin::user()->id,
            "is_owner" => $is_owner,
        ];
        $has_comment = AdminAccountOperate::getByObjId($data['obj_id'], AdminAccountOperate::ACCOUNT_TYPE_COMMENT,
            $data['obj_type']);
        if ($has_comment) {
            $error = new MessageBag([
                'title' => '评论失败,此内容已有运营评论'
            ]);
            return redirect('/admin/blank/select/comment/' . $data['obj_id'])->with(compact('error'));
        }
        $result = DbComment::addComment($data);
        Queue::insertQueue('CommentDig/afterComment', [
            'obj_id' => $data['obj_id'],
            'uid' => $data['uid'],
            'comment' => $data['content'],
            'cmt_id' => $result,
            'time' => time(),
        ]);

        //更新es
        Queue::insertQueue('Comment/addComment', [
            'obj_id' => $data['obj_id'],
            'cmt_id' => $result
        ]);

        // 返回结果
        if ($result) {
            AdminAccountOperate::addData([
                "operate_type" => AdminAccountOperate::ACCOUNT_TYPE_COMMENT,
                "uid" => $data['uid'],
                "admin_id" => Admin::user()->id,
                "addtime" => date('Y-m-d H:i:s', time()),
                "obj_id" => $data['obj_id'],
                "obj_type" => self::OBJ_TYPE,
                "content" => $data['content'],
                'comment_id' => $result
            ]);
            $this->_blankHandle($data, $result);
            HaveRecommend::setHaveInteract($data['uid'], $data['obj_id']);
            $success = new MessageBag([
                'title' => '评论成功'
            ]);
            return redirect('/admin/blank/select/comment/' . $data['obj_id'])->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '评论失败'
            ]);
            return redirect('/admin/blank/select/comment/' . $data['obj_id'])->with(compact('error'));
        }

    }

    public function _blankHandle($data, $comment_id)
    {
        // 计数器图片评论加1
        BlankCounter::increaseBlankCounter($data['obj_id'], BlankCounter::ACT_COMMENT);
        BlankCounter::increaseBlankCounter($data['obj_id'], BlankCounter::ACT_MASTER_COMMENT);

        $aQueueData = [
            'act' => 'comment',
            'blank_id' => $data['obj_id'],
            'act_uid' => $data['uid'],
            'cmt_id' => $comment_id,
            'reply_uid' => $data['to_uid'],
            'from_platform' => $data['from_platform'],
        ];
        Queue::insertQueue('Blank/interaction', $aQueueData);
    }

    //评论账号列表
    public function commentAccount(Request $request, \App\Admin\Extensions\WorkContent $content)
    {
        $request = $request->all();
        return $content
            ->body(self::commentAccountList($request));

    }

    public static function commentAccountList($request)
    {
        $account_list = AdminAccount::getAllByAdminId(Admin::user()->id);
        $user_infos = [];
        if ($account_list && is_array($account_list)) {
            $uids = array_column($account_list, 'uid');
            if ($uids && is_array($uids)) {
                $user_infos = Member::getUsers($uids);
            }
            foreach ($account_list as &$account_info) {
                $account_info['nick'] = (string)$user_infos[$account_info['uid']]['nick'];
            }
        }

        $gridModel = new pGridDataModel($account_list, count($account_list), []);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disablePagination();
            $grid->disableFilter();
            $grid->disableActions();
            $grid->disableRowSelector();
            $grid->column('id');
            $grid->column('uid', '用户id');
            $grid->column('nick', '用户昵称');
            $grid->column('addtime', '添加时间');
        });
        $list = $listGrid->render();
        return $list;
    }

    //添加运营评论账号
    public function addCommentAccount(Request $request, \App\Admin\Extensions\WorkContent $content, $id)
    {
        return $content
            ->body(self::commentEditAction($request, $id));
    }

    public function commentEditAction($request, $id)
    {
        $form = new Form([]);
        $form->number('uid', 'uid')->required('必填');
        $form->action('/admin/blank/select/comment/' . $id . '/commentaccount/save');
        return $form->render();
    }

    public function commentAccountSubmit(Request $request, $id)
    {
        $request = $request->all();
        $uid = (int)$request['uid'];
        $admin_id = Admin::user()->id;
        $has_account = AdminAccount::getByAdminIdAndUid($uid, $admin_id);
        if ($uid && !$has_account) {
            $data = [
                'uid' => $uid,
                'admin_id' => $admin_id,
                'account_type' => AdminAccount::ACCOUNT_TYPE_COMMENT,
                'addtime' => date('Y-m-d H:i:s', time()),
                'account_status' => AdminAccount::STATUS_NORMAL
            ];
            AdminAccount::addData($data);
            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect("/admin/blank/select/comment/{$id}/commentaccount")->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => '添加失败'
        ]);
        return redirect("/admin/blank/select/comment/{$id}/commentaccount")->with(compact('error'));

    }

    //运营点赞
    public function adminLike()
    {
        return <<<SCRIPT
            $('.addLike').click(function() {
                var id = $(this).data('id');
                $.ajax({type:"get",url:"like/"+id,success:function(data){
                    if(data != '') {
                        $('#like'+id).html(data+"已点赞");
                        $('#like'+id).addClass('btn-success');
                        $('#like'+id).css('color','#FFFFFF');
                        $('#like'+id).attr('disabled', 'disabled');
                    }
                }});
            });    
           
            $('.addBusiness').click(function() {
                var id = $(this).data('id');
                console.log($(this).hasClass('addBusiness'));
                 if($(this).hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                $.ajax({type:"get",url:"business/"+id+"/"+type,success:function(data){
                    if(data) {
                       if (type == 'remove'){
                            $('#business'+id).removeClass('btn-success');
                            $('#business'+id).addClass('btn-default');
                            $('#business'+id).css('color','#444');                        
                       }else{
                        $('#business'+id).addClass('btn-success');
                        $('#business'+id).css('color','#FFFFFF');
                       } 
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                    }
                }});
            });
            
                $('.addDisplayBusiness').click(function() {
                var id = $(this).data('id');
                console.log($(this).hasClass('addDisplayBusiness'));
                 if($(this).hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                $.ajax({type:"get",url:"displayBusiness/"+id+"/"+type,success:function(data){
                    if(data) {
                       if (type == 'remove'){
                            $('#display'+id).removeClass('btn-success');
                            $('#display'+id).addClass('btn-default');
                            $('#display'+id).css('color','#444');                        
                       }else{
                        $('#display'+id).addClass('btn-success');
                        $('#display'+id).css('color','#FFFFFF');
                       } 
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                    }
                }});
            });
SCRIPT;
    }

    public function adminCopy()
    {
        return <<<SCRIPT
        $('.copyH5').click(function() {
            var id = $(this).data('id');
            $.ajax({type:"get",url:"copy/"+id,success:function(url){
            var tempInput = document.createElement("input");
            tempInput.value = url;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            }});
        });
SCRIPT;
    }

    /**
     * @param $id
     * @param $type
     * @return int|mixed|string
     */
    public function editBusiness($id, $type)
    {
        $info = ContentSignExtend::getExtendInfoByNoteIds($id);

        if ($type == "add") {
            $data = [
                "obj_id" => $id,
                "is_business" => ContentSignExtend::IS_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s', time());
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            } else {
                $data["addtime"] = date('Y-m-d H:i:s', time());
                $data["obj_type"] = IdParse::getType($id);
                $rs = ContentSignExtend::addExtendInfo($data);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['SOFT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        } else {
            $data = [
                "obj_id" => $id,
                "is_business" => ContentSignExtend::NOT_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s', time());
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['NOT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        }
        return $rs;
    }

    public function displayBusiness($id, $type)
    {
        $info = ContentSignExtend::getExtendInfoByNoteIds($id);

        if ($type == "add") {
            $data = [
                "obj_id" => $id,
                "is_display_business" => ContentSignExtend::IS_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s');
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            } else {
                $data["addtime"] = date('Y-m-d H:i:s', time());
                $data["obj_type"] = IdParse::getType($id);
                $rs = ContentSignExtend::addExtendInfo($data);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['HARD_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        } else {
            $data = [
                "obj_id" => $id,
                "is_display_business" => ContentSignExtend::NOT_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s');
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['NOT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        }
        return $rs;
    }

    public function saveLike($id)
    {
        $rs = '';
        $hasLike = AdminAccountOperate::getByObjId($id, AdminAccountOperate::ACCOUNT_TYPE_LIKE, self::OBJ_TYPE);
        if ($hasLike) {
            $rs = Admin::user()->find($hasLike['admin_id'])->name;
        } else {
            AutoAction::autoLike($id, AutoAction::SOURCE_ADMIN);
            AdminAccountOperate::addData([
                "operate_type" => AdminAccountOperate::ACCOUNT_TYPE_LIKE,
                "uid" => (int)0,
                "admin_id" => Admin::user()->id,
                "addtime" => date('Y-m-d H:i:s', time()),
                "obj_id" => $id,
                "obj_type" => self::OBJ_TYPE,
                "content" => ''
            ]);
            $hasLike = AdminAccountOperate::getByObjId($id, AdminAccountOperate::ACCOUNT_TYPE_LIKE, self::OBJ_TYPE);
            if ($hasLike) {
                $rs = Admin::user()->find($hasLike['admin_id'])->name;
            }
        }
        return $rs;
    }

    //复制H5链接
    public function copyUrl($id)
    {
        return Hhzurl::h5BlankShow($id);
    }

}